package com.gagakuai.util;


import com.gagakuai.exception.SettementException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/*
 * 邮件发发送工具类
 * @author flipped
 * @date 2021-12-22
 * @version 1.0.0
 */
@Component
public class EmailUtils {

    @Value("${hx.mail.from}")
    private String from;

    @Value("${hx.mail.host}")
    private String host;

    @Value("${hx.mail.port}")
    private String port;

    @Value("${hx.mail.protocol}")
    private String protocol;

    @Value("${hx.mail.username}")
    private String username;

    @Value("${hx.mail.password}")
    private String password;

    public void sendEmail(String to, String title, String content) {
        // 发件人电子邮箱
        // String from = "mrsggyx@chinaexpressair.com";
        // 指定发送邮件的主机为 localhost
        // String host = "mail.chinaexpressair.com";
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.port", port);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties);
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // Set Subject: 头部头字段
            message.setSubject(title);
            // 设置消息体
            message.setText(content);
            Transport transport = session.getTransport();
            transport.connect(host, username, password);
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();
        } catch (MessagingException mex) {
            mex.printStackTrace();
            throw new SettementException(mex.getMessage());
        }
    }

}
